$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_fbch_m")
    const dgrid1 = $NG.getCmpApi("p_form_fbch_d3")
    const dgrid2 = $NG.getCmpApi("p_form_fbch_d2")
    const getHeadValue = (str) => mstform.getItem(str).getValue()
    let saveLock = false

    isSaveLock()

    const btn = ['save', 'check']
    btn.forEach(item => {
        useBeforeClick(() => {
            if (saveLock) {
                $NG.alert("当前合同名称已包含一张分包策划，请勿重复创建！")
                return false
            }
        }, item)
    })
    useUpdateRows(() => {
        sumAmt()
    }, "p_form_fbch_d3")

    function sumAmt() {
        const rows = dgrid1.getRows()
        rows.forEach(item => {
            if ((Number(item.u_gcl) || 0) > (Number(item.u_ygcl) || 0)) {
                $NG.alert("工程量不能超过原工程量")
                item.u_gcl = 0
            }
            item.u_fyxj = (Number(item.u_cl) || 0) + (Number(item.u_jx) || 0) + (Number(item.u_qtfy) || 0) + (Number(item.u_sj) || 0)

            item.u_nfb = (Number(item.u_nfbje) || 0) * (Number(item.u_gcl) || 0)
            item.u_clje = (Number(item.u_cl) || 0) * (Number(item.u_gcl) || 0)
            item.u_jxje = (Number(item.u_jx) || 0) * (Number(item.u_gcl) || 0)
            item.u_qtfyje = (Number(item.u_qtfy) || 0) * (Number(item.u_gcl) || 0)
            item.u_sjje = (Number(item.u_sj) || 0) * (Number(item.u_gcl) || 0)
            item.u_u_dydcbhtje = (Number(item.u_gcl) || 0) * (Number(item.u_dj) || 0)
            item.u_fyxjje = (Number(item.u_clje) || 0) + (Number(item.u_jxje) || 0) + (Number(item.u_qtfyje) || 0) + (Number(item.u_sjje) || 0)
            item.u_lrje = (Number(item.u_dydcbhtje) || 0) - (Number(item.u_nfb) || 0) - (Number(item.u_fyxjje) || 0)
            item.u_lr = (Number(item.u_gcl) || 0) && (Number(item.u_lrje) || 0) / (Number(item.u_gcl) || 0)
            item.u_hj = (Number(item.u_gcl) || 0) * (Number(item.u_dj) || 0)
        })
        dgrid1.refreshView()
    }

    useValuesChange(() => {
        getCntCbInfoByPhid()
        isSaveLock()
        getHtDetail3Info()
        getHtDetail1Info()
    }, "p_form_fbch_m.u_htmc")

    //getCntCbInfoByPhid
    function getCntCbInfoByPhid() {
        const phid = mstform.getItem("u_htmc").getValue()
        if (!phid) return
        $NG.execServer("getCntCbInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const data = JSON.parse(res.data)[0].extendObjects
            const arr = [
                {
                    key: "phid_pc",
                    value: {
                        label: data.phid_pc_exname,
                        value: data.phid_pc
                    }
                },
                {
                    key: "u_xmjc",
                    value: data.user_xmjc
                },
                {
                    key: "u_htbh",
                    value: data.cnt_no
                },
                {
                    key: "u_htje",
                    value: data.user_htje
                }, {
                    key: "u_xmchmc",
                    value: {
                        label: data.xmch_name,
                        value: data.xmch_phid
                    }
                }, {
                    key: "u_xmchlrl",
                    value: data.xmch_lrl
                }
            ]
            setHeadValue(arr)
        })
    }

    // 获取合同清单明细3
    function getHtDetail3Info() {
        const phid = mstform.getItem("u_htmc").getValue()
        if (!phid) return
        $NG.execServer("getHtDetail3Info", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                const it = { ...item.extendObjects }
                value.push({
                    ...it,
                    u_ygcl: it.u_gcl,
                    u_dw: it.u_jldw,
                    u_dw_EXName:it.msname
                })
                return value
            }, [])
            const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
            dgrid1.addRows([...arr])
        })
    }

    function getHtDetail1Info() {
        const phid = mstform.getItem("u_htmc").getValue()
        if (!phid) return
        $NG.execServer("SELECT", { sql: `select rel_key1,u_fbmc from p_form_htq_d2 d left join p_form_htq_m m on m.phid = d.pphid where u_yzht = '${phid}'` }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                value.push({
                    u_fbxmmc: item.extendObjects.u_fbmc,
                    rel_key1: item.extendObjects.rel_key1
                })
                return value
            }, [])
            dgrid2.addRows([...datas])
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }

    function isSaveLock() {
        const phid = mstform.getItem("u_htmc").getValue()
        const mid = mstform.getValues().phid || '0'
        if (!phid) return
        $NG.execServer("SELECT", { sql: `select phid from p_form_fbch_m where u_htmc = '${phid}' and phid != '${mid}'` }, (res) => {
            if (res.count !== 0) {
                $NG.alert("当前合同名称已包含一张分包策划，请勿重复创建！")
                saveLock = true
            } else {
                saveLock = false
            }
        })
    }
    // 赋值
    function setHeadValue(datas) {
        datas.forEach(item => {
            try {
                mstform.getItem(item.key).setValue(item.value)
            } catch (err) {
                console.log(`err`, err, item);
            }
        })
    }
})
